﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RuoVea.ExDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuoVea.ExFilter
{
    /// <summary>
    /// 
    /// </summary>
    public interface IRestfulFilterLog 
    {
        #region 全局日志记录 请求日志拦截

        /// <summary>
        /// 全局日志记录 请求日志拦截
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next);
        #endregion

        #region 注入 全局异常处理 [进行全局的异常日志收集]
        /// <summary>
        /// 注入 全局异常处理 [进行全局的异常日志收集]
        /// </summary>
        /// <param name="context"></param>
        void OnException(ExceptionContext context);
        #endregion

        #region 对资源型信息进行过滤。常用于防盗链/资源缓存 -- IResourceFilter
        /// <summary>
        /// 对资源型信息进行过滤。常用于防盗链/资源缓存
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        void OnResourceExecuted(ResourceExecutedContext context);

        /// <summary>
        /// 对资源型信息进行过滤。常用于防盗链/资源缓存
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        void OnResourceExecuting(ResourceExecutingContext context);

        #endregion

        #region 对结果进行统一 -- IResultFilter
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        void OnResultExecuted(ResultExecutedContext context);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        void OnResultExecuting(ResultExecutingContext context);
        #endregion
    }
}


/// <summary>
/// 
/// </summary>
public class ModelValidateAttribute : ActionFilterAttribute
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            //获取验证失败的模型字段
            var errors = context.ModelState
                .Where(e => e.Value?.Errors?.Count > 0)
                .Select(e => e.Value?.Errors.First().ErrorMessage)
                .ToList();
            RestfulResult result = new RestfulResult()
            {
                Code = RuoVea.ExEnum.CodeStatus.UnsupportedMediaType,
                Message = string.Join("|", errors)
            };
            context.Result = new JsonResult(result);
        }
    }
}